package com.hcbd.tdwt.base;

import static com.hcbd.tdwt.base.GlobalParams.sendBeidouMsgSignalEnable;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BdToolFactory;
import com.cy.translucentparent.StatusNavUtils;
import com.google.android.material.snackbar.Snackbar;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.ui.common.dialog.WarnDialog;
import com.hcbd.tdwt.ui.xingyu.dialog.LoadingDialog;
import com.hcbd.tdwt.ui.xingyu.dialog.OldProtocolDialog;
import com.hcbd.tdwt.ui.xingyu.fragment.AppSendSOSFragment;
import com.hcbd.tdwt.ui.xingyu.vo.Position;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.hcbd.tdwt.util.StringUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

abstract public class BaseActivity extends AppCompatActivity {
    //警告框
    private WarnDialog warnDialog;
    //加载弹框
    public LoadingDialog loadDialog;


    protected boolean isRefreshing;
    private Fragment currentFragment;
    protected Bundle savedInstanceState;
    private String TAG = "BaseActivity";
    public Context my_context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if(BdToolFactory.app_type==BdToolFactory.XY_BG_TYPE||BdToolFactory.app_type==BdToolFactory.XY_PDA_BG_TYPE){
            StatusNavUtils.setStatusNavBarColor(this, getColor(R.color.deep_black), getColor(R.color.white));
            setAndroidNativeLightStatusBar(false);
            getWindow().setNavigationBarColor(getColor(R.color.deep_black));
        }else {
            StatusNavUtils.setStatusBarColor(this,0x00000000);
        }
        this.savedInstanceState=savedInstanceState;
        initProgressDialog();
    }
    //设置状态栏字体颜色
    public  void setAndroidNativeLightStatusBar(boolean dark) {
        View decor = getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }
    protected abstract void init();



    private Toast my_toast;  // Toast
    @SuppressLint("ShowToast")
    public void toast(String tip){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(my_toast!=null){
                    my_toast.cancel();
                    my_toast = null;
                }
                my_toast = Toast.makeText(my_context,tip,Toast.LENGTH_SHORT);
                my_toast.show();
            }
        });
    }

    /**
     * 显示警告框
     *
     * @param onClickListener
     */
    public void showWarnDialog(String str, View.OnClickListener onClickListener) {
        if (warnDialog == null) {
            warnDialog = new WarnDialog();
        }
        if (warnDialog.isAdded()) return;
        warnDialog.setData(this, str, onClickListener);
        warnDialog.show(getFragmentManager(), "");
    }
    @Override
    protected void onResume() {
        super.onResume();
        MainApp.getInstance().mActivity=this;
        initProgressDialog();
    }
    //加载弹框
    public LoadingDialog mProgressDialog;
    /**
     * 隐藏警告框
     */
    public void hideWarnDialog() {
        if (warnDialog != null) {
            warnDialog.dismiss();
        }
    }
    /**
     * 初始化加载框
     */
    private void initProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new LoadingDialog(this);
        }
        MainApp.getInstance().mProgressDialog = mProgressDialog;
    }
    /**
     * 获取视图
     *
     * @return
     */
    public View getView() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        FrameLayout content = view.findViewById(android.R.id.content);
        return content.getChildAt(0);
    }
    public void popupMsg(final String msg) {
        //回到主线程执行run里面的函数
        runOnUiThread(() -> {
            hideKeyboard();
            Snackbar.make(getView(), msg, Snackbar.LENGTH_SHORT).show();
        });
    }

    public String getTextStr(EditText editText){
        return editText.getText().toString().trim();
    }
    /**
     * 隐藏软键盘
     */
    public void hideKeyboard() {
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
      /*  if(bdMsgBroadcast!=null) {
            MainApp.getInstance().unregisterReceiver(bdMsgBroadcast);
        }*/
        EventBus.getDefault().unregister(this);
        isRefreshing=false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideInputKeyBord();
    }

    /**
     * 检查隐式Intent是否可用
     * 用于打开外部应用前的判断
     *
     * @param intent 目标Intent
     * @return true 或 false
     */
    public boolean checkIntent(Intent intent) {
        ComponentName componentName = intent.resolveActivity(this.getPackageManager());
        if (componentName == null) {
            return false;
        }
        return true;
    }
    /**
     * 显示加载框
     */
    public void showLoading(String str) {
        if (loadDialog == null) {
            loadDialog = new LoadingDialog(this,str);
        }
        loadDialog.setTips(str);

        LoadingDialog.showDialog(loadDialog);
    }

    /**
     * 隐藏加载框
     */
    public void hideLoading() {
        if (loadDialog == null) return;
        LoadingDialog.shutDown(loadDialog);
    }
    protected void switchFragment(Fragment targetFragment, int frameLayutId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            if(currentFragment!=null){
                transaction.hide(currentFragment).add(frameLayutId, targetFragment).commit();
            }else{
                transaction.add(frameLayutId, targetFragment).commit();
            }
        } else {
            transaction.hide(currentFragment).show(targetFragment).commit();
        }
        currentFragment = targetFragment;
    }
    /**
     * 显示系统软键盘
     */
    public void showInputKeybord(final View view) {
        view.postDelayed(() -> {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            if (null != imm) {
                view.requestFocus();
                imm.showSoftInput(view, 0);
            }
        }, 100);
    }



    //申请权限请求码
    protected int permissionRequestCode = 10;


    protected static final String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
   /*         Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_ADVERTISE*/};


    /**
     * 隐藏Activity所在Window的系统软键盘
     */
    public void hideInputKeyBord() {
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputMethodManager) {
            inputMethodManager.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
    }
    private OldProtocolDialog oldProtocolDialog;
    /**
     * 显示带取消的警告框
     */
    public void showOldProtocolDialog(String content,OldProtocolDialog.OnCloseListener onCloseListener) {
        if (oldProtocolDialog == null) {
            oldProtocolDialog = new OldProtocolDialog();
        }
        if (oldProtocolDialog.isAdded()) return;
        oldProtocolDialog.setData(this, content,onCloseListener);
        oldProtocolDialog.show(this.getFragmentManager(), "");
    }
    //判断当前点击屏幕的地方是否是软键盘：
    public boolean isShouldHideInput(View v, MotionEvent event) {
        if ((v instanceof EditText)) {
            int[] leftTop = {0, 0};
            v.getLocationInWindow(leftTop);
            int left = leftTop[0], top = leftTop[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
    /**
     * 实现点击空白处，软键盘消失事件
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideInputKeyBord();
            }
        }
        return super.dispatchTouchEvent(ev);
    }
   public void setStatusNavBar(int color_status,int color_nav,boolean dark){
       StatusNavUtils.setStatusNavBarColor(this,color_status,color_nav);
       setAndroidNativeLightStatusBar(dark);
   }
    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param serviceName
     *            是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public boolean isServiceWork(String serviceName) {
        boolean isWork = false;
        ActivityManager myAM = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(40);
        if (myList.size() <= 0) {
            return false;
        }
        for (int i = 0; i < myList.size(); i++) {
            String mName = myList.get(i).service.getClassName();
            if (mName.equals(serviceName)) {
                isWork = true;
                break;
            }
        }
        return isWork;
    }
   public void initMsgRegister(){
       if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
       }

   }
    /**
     * dp转为px
     *

     * @param dipValue dp值
     * @return
     */
    public int dip2px(float dipValue) {
        Resources r = getResources();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dipValue, r.getDisplayMetrics());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e(TAG, "按键事件: "+keyCode);
        // SOS 按键
        if(keyCode==KeyEvent.KEYCODE_F1){
            SharedPreferencesUtil sp = new SharedPreferencesUtil(this);
            int sos_pro_type=sp.getAttributeInt(Constant.SOS_PRO);
            String phone = sp.getAttribute(Constant.LAST_SOS_NUMBER);
            if(phone==null||phone.equals("")){phone="110110110";}
            if(BeidouBoxParams.gpsLonDou==0||BeidouBoxParams.gpsLatDou==0){
                toast("当前APP定位信息未获取请等待!");
                return super.onKeyDown(keyCode, event);
            }
            int beidouSignal = BeidouBoxParams.getBdSignal();
            if (beidouSignal < sendBeidouMsgSignalEnable) {
                toast("信号不好，请移动终端位置");
                return super.onKeyDown(keyCode, event);
            }
            if (!BeidouBoxParams.isBoxConnectNormal) {
                toast("请连接终端!");
                return super.onKeyDown(keyCode, event);
            }
            if(BeidouBoxParams.sentWaitSec>0){
                toast("频度未到!");
                return super.onKeyDown(keyCode, event);
            }
            Position position = new Position();
            position.setLongitude(BeidouBoxParams.gpsLonDou);
            position.setLatitude(BeidouBoxParams.gpsLatDou);
            position.setAltitude(GlobalParams.gpsAltitude);
            position.setTime(Long.parseLong(DateUtils.getTimeStamp()));
            //没有公网的情况使用北斗网发送
            AppSendSOSFragment.sendByMsg(sos_pro_type,phone, position, "00", "00", 1);
        }
        return super.onKeyDown(keyCode, event);
    }
}
